#!/usr/bin/python
# -*- coding: UTF-8 -*-
import json
import os.path
import shutil
import sys
from imp import reload

reload(sys)
sys.setdefaultencoding('utf8')
import pandas as pd


class ReadExcel:
    def __init__(self, excelPath):
        self.m_excelPath = excelPath
        self.m_musicName = list()

    def readExcel(self):
        df = pd.read_excel(self.m_excelPath)
        # read_excel(self.m_excelPath,sheet_name='音效名称',usecols=[1])
        data = df.values
        customNameList = list()
        if df.get("CustomName") is not None:
            for index in range(len(df['CustomName'].values)):
                if pd.isna(df['CustomName'].values[index]):
                    customNameList.append("")
                else:
                    customNameList.append(df['CustomName'].values[index])

        for index in range(len(data)):
            lines = data[index]
            serialNumber = None
            for otherIndex in range(len(lines)):
                if lines[otherIndex] is not None and (not pd.isna(lines[otherIndex])):
                    if isinstance(lines[otherIndex], int):
                        serialNumber = otherIndex + 1
                        break
            if serialNumber is not None and (not pd.isna(lines[serialNumber])):
                # print("musicIndex:{},musicName:{}".format(index + 1, lines[serialNumber]))
                customName = None
                if customNameList:
                    customName = customNameList[index]
                musicInfo = {"musicName": lines[serialNumber], "index": (index + 1),"customName":customName}
                self.m_musicName.append(musicInfo)

class CopyMusicRes:
    def __init__(self, musicRes):
        self.m_musicRes = musicRes
        self.m_musicCopyRes = musicRes + "/copy"

    def copyRes(self):
        if os.path.exists(self.m_musicCopyRes):
            shutil.rmtree(self.m_musicCopyRes, True)
        os.mkdir(self.m_musicCopyRes)
        for root, dirs, files in os.walk(self.m_musicRes):
            for f in files:
                kind = os.path.splitext(f)[-1]
                if kind is not None:
                    if kind == ".mp3":
                        # musicName = os.path.basename(f)
                        shutil.copyfile(self.m_musicRes + "/" + f, self.m_musicCopyRes+"/"+f)


class CheckExcelMatchRes:
    def __init__(self, musicNameList, musicRes, prefixName, specialList):
        self.m_musicNameList = musicNameList
        self.m_musicRes = musicRes
        self.m_prefixName = prefixName
        self.m_specialList = specialList
        self.m_inMusicResList = list()
        self.m_excludeMusicResList = list()

    def checkFileExit(self, musicName, musicPos,customName,specialList = None):
        musicName = self.m_prefixName + musicName
        musicNamePath = self.m_musicRes + "/" + musicName + ".mp3"
        musicChangeName = "Sound_" + str(musicPos)
        haveCustomName = False
        #优先查看是否有自定义的名字
        if customName and customName is not None and not pd.isna(customName):
            haveCustomName = True
            musicChangeName = musicChangeName + customName

        if specialList is not None:
            if haveCustomName:
                musicChangeName = musicChangeName + str(specialList[0])
            else:
                musicChangeName = musicChangeName + "_" + specialList[1] + str(specialList[0])
        musicInfo = {"musicName": musicName, "musicChangeName": musicChangeName, "musicPos": musicPos}
        if os.path.exists(musicNamePath):
            self.m_inMusicResList.append(musicInfo)
        else:
            self.m_excludeMusicResList.append(musicInfo)

    def check(self):
        # check list musicName in musicRes
        for index in range(len(self.m_musicNameList)):
            musicName = self.m_musicNameList[index]["musicName"]
            musicPos = self.m_musicNameList[index]["index"]
            customName = self.m_musicNameList[index]["customName"]
            isSpecial = False
            specialCount = 0
            specialChangeName = ""
            for specialIndex in range(len(self.m_specialList)):
                specialStr = self.m_specialList[specialIndex][0]
                if specialStr in musicName:
                    isSpecial = True
                    specialCount = self.m_specialList[specialIndex][1]
                    specialChangeName = self.m_specialList[specialIndex][2]
                    break

            if isSpecial:
                for count in range(0, specialCount):
                    count = count + 1
                    tempMusicName = musicName + str(count)
                    specialList = [count, specialChangeName]
                    print("specialList {}".format(tempMusicName))
                    self.checkFileExit(tempMusicName, musicPos,customName,specialList)
            else:
                self.checkFileExit(musicName, musicPos,customName)


class GenerateLuaFileAndChangeFileName:
    def __init__(self, luaFilePath, inMusicNameList, excludeMusicNameList, musicResPath, levelName):
        self.m_luaFile = luaFilePath
        self.m_inMusicNameList = inMusicNameList
        self.m_excludeMusicNameList = excludeMusicNameList
        self.m_musicResPath = musicResPath
        self.m_levelName = levelName
        self.m_nameAndDescribe = list()

    def changeFileName(self):
        for index in range(len(self.m_inMusicNameList)):
            musicName = self.m_inMusicNameList[index]["musicName"]
            musicPath = self.m_musicResPath + "/" + musicName + ".mp3"
            renameMusicUpperName = self.m_inMusicNameList[index]["musicChangeName"]
            renameMusicName = self.m_levelName + "_" + renameMusicUpperName
            renameMusicPath = self.m_musicResPath + "/" + renameMusicName + ".mp3"
            if os.path.exists(musicPath):
                os.rename(musicPath, renameMusicPath)
                tempDic = {"musicName": musicName, "renameMusicName": renameMusicName, "renameMusicUpperName": renameMusicUpperName}
                self.m_nameAndDescribe.append(tempDic)
            else:
                print("谁在运行的时候删掉了这个 {} 文件请检查".format(musicName))

    def generateLuaFile(self):
        if os.path.exists(self.m_luaFile):
            os.remove(self.m_luaFile)
        luaStr = "{ \n"
        for index in range(len(self.m_nameAndDescribe)):
            musicName = self.m_nameAndDescribe[index]["musicName"]
            renameMusicName = self.m_nameAndDescribe[index]["renameMusicName"]
            renameMusicUpperName = self.m_nameAndDescribe[index]["renameMusicUpperName"]
            tempStr = str(renameMusicName).upper()
            tempStr = tempStr + " = " + "\"" + self.m_levelName + "Sounds/" + renameMusicName + ".mp3\"" + ", "
            tempStr = tempStr + " -- " + musicName + " \n"
            luaStr = luaStr + tempStr

        luaStr = luaStr + "} \n\n\n\n"

        if len(self.m_excludeMusicNameList) > 0:
            luaStr = luaStr + " \n --以下不用拷贝，检查以下列表中资源是否在资源目录中 \n"
            for index in range(len(self.m_excludeMusicNameList)):
                musicName = self.m_excludeMusicNameList[index]["musicName"]
                luaStr = luaStr + musicName + "\n"

        file = open(self.m_luaFile, "w+")
        if file:
            file.write(luaStr)
        file.close()


class ReadConfig:
    def __init__(self, configFile):
        self.m_configFile = configFile
        self.m_specialList = list()
        self.m_prefixName = ""

    def readConfig(self):
        with open(self.m_configFile) as f:
            data = json.load(f)
            if data is not None:
                self.m_prefixName = data.get("prefixName")
            specialList = data.get("specialList")
            for index in range(len(specialList)):
                lines = specialList[index]
                self.m_specialList.append(lines)


if __name__ == '__main__':
    argvLen = len(sys.argv) - 1
    if argvLen < 3:
        print("参数一 音效需求xlsx的路径 \n")
        print("参数二 音效需求的资源路径 \n")
        print("关卡名字")
        sys.exit()
    print("begin")
    jsonPath = os.path.split(os.path.realpath(__file__))[0] + "/generateMusicDef.json"
    config = ReadConfig(jsonPath)
    config.readConfig()
    args = sys.argv
    musicXlsxPath = args[1]
    musicResPath = args[2]
    levelName = args[3]
    luaFile = musicResPath + "/" + levelName + "SoundDef.lua"
    if os.path.exists(luaFile):
        os.remove(luaFile)
    excel = ReadExcel(
        musicXlsxPath)
    copyMusic = CopyMusicRes(musicResPath)
    excel.readExcel()
    copyMusic.copyRes()
    # 有些音效会有特殊的，比如中奖连线 一般都会有 123 需要特殊处理下
    specialList = config.m_specialList
    prefixName = config.m_prefixName
    check = CheckExcelMatchRes(excel.m_musicName, copyMusic.m_musicCopyRes, prefixName, specialList)
    check.check()
    lua = GenerateLuaFileAndChangeFileName(luaFile, check.m_inMusicResList, check.m_excludeMusicResList,
                                           copyMusic.m_musicCopyRes, levelName)
    lua.changeFileName()
    lua.generateLuaFile()

    del copyMusic
    del excel
    del check
    print("end")

# See PyCharm help at https://www.jetbrains.com/help/pycharm/
